package prj.carmap.mobile.activity;

import java.util.List;

import org.apache.http.entity.StringEntity;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import prj.carmap.mobile.model.SellerInfo;
import prj.carmap.mobile.model.ServiceItem;
import prj.carmap.mobile.process.AutoServiceProcess;
import prj.carmap.mobile.process.LiveServiceProcess;
import prj.carmap.mobile.process.SellerTypeProcess;
import prj.carmap.mobile.util.AccessLogUtil;
import prj.carmap.mobile.util.ImageLoader;
import prj.carmap.mobile.util.ImgUtil;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar.LayoutParams;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.baidu.mapapi.navi.BaiduMapNavigation;
import com.baidu.mapapi.navi.NaviPara;
import com.baidu.platform.comapi.basestruct.GeoPoint;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.miaowang.salad.activity.MineInfoActivity;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

/**
 * 商家界面
 * 
 */
public class SellerActivity extends SherlockActivity implements
		OnItemClickListener {

	/** 商家信息 */
	private SellerInfo currentSeller;
	private TextView countPic;
	protected GridView gridView;
	protected ImageLoader imageLoader = new ImageLoader();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Application app = (Application) this.getApplication();

		CarmapApplication.currentPage = getIntent().getStringExtra("flag") == null ? "type"
				: getIntent().getStringExtra("flag");
		CarmapApplication.addActivity(this);
		setContentView(R.layout.activity_seller_detail);

		// Inflate the custom view
		View customNav = LayoutInflater.from(this).inflate(R.layout.nav_seller_title_view, null);
		getSupportActionBar().setDisplayShowCustomEnabled(true);
		getSupportActionBar().setDisplayShowHomeEnabled(false);
		getSupportActionBar().setDisplayShowTitleEnabled(false);

		
		((TextView) customNav.findViewById(R.id.nav_title)).setText( "商家详情" );
		LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.CENTER);
		getSupportActionBar().setCustomView(customNav);
		customNav.setLayoutParams(lp);
		Button returnBtn = (Button) customNav.findViewById(R.id.return_prev);
		returnBtn.setOnClickListener(new Button.OnClickListener() {// 创建监听
					public void onClick(View v) {
						SellerActivity.this.finish();
					}
				});
		Button mapBtn = (Button) customNav.findViewById(R.id.return_map);
		mapBtn.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				Intent in = new Intent(SellerActivity.this, MapOverlayActivity.class);
				in.putExtra("lat", currentSeller.latitude+"");
				in.putExtra("lon", currentSeller.longitude+"");
				in.putExtra("name", currentSeller.sellerName);
				SellerActivity.this.startActivity(in);
				
			}
		});
		initMenuItem();

		TextView sellerName = (TextView) this.findViewById(R.id.seller_name);
		// TextView distance = (TextView)
		// this.findViewById(R.id.seller_distance);
		TextView address = (TextView) this.findViewById(R.id.seller_address);
		TextView call = (TextView) this.findViewById(R.id.seller_phone);
		TextView description = (TextView) this
				.findViewById(R.id.seller_description);
		// ImageView sellerPic = (ImageView) this.findViewById(R.id.seller_img);
		// View loading = (View) this.findViewById(R.id.seller_img_loading);
		// countPic = (TextView)this.findViewById(R.id.countPic);
		// 商家 拨打电话
		View callSeller = (View) this.findViewById(R.id.call_seller_image);
		currentSeller = (SellerInfo) this.getIntent().getExtras()
				.get("currentSeller");
		final String phone = currentSeller.telephone;
		callSeller.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (phone == null || "".equals(phone.trim())) {
					return;
				}

				new AlertDialog.Builder(SellerActivity.this)
						.setTitle(R.string.confirm_call)
						.setMessage("拨打电话" + phone + "?")
						.setPositiveButton(
								R.string.submit,
								new android.content.DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										Intent phoneIntent = new Intent(
												"android.intent.action.CALL",
												Uri.parse("tel:" + phone));
										SellerActivity.this
												.startActivity(phoneIntent);
										// 发送拨打电话log给服务器
										StringEntity log = AccessLogUtil
												.createAccessLogParam(
														currentSeller.sellerId,
														phone);
										if (log != null)
											new AsyncHttpClient()
													.post(SellerActivity.this,
															CarmapApplication.SERVER_URL
																	+ "/rest/accesslog",
															log,
															"application/json",
															new AsyncHttpResponseHandler());
									}
								}).setNegativeButton(R.string.cancel, null)
						.show();
			}
		});

		// 商家 到这去
		View goSeller = (View) this.findViewById(R.id.go_seller_image);
		goSeller.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (currentSeller == null)
					return;

				SellerActivity.this.startNavi(v, currentSeller.latitude,
						currentSeller.longitude);
			}
		});
		gridView = (GridView) findViewById(R.id.seller_detail_gridview);
		if (currentSeller.sellerPics != null
				&& currentSeller.sellerPics.size() > 0) {
			gridView.setAdapter(new ImageAdapter());
			gridView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					Intent intent = new Intent(SellerActivity.this,
							TestanroidpicActivity.class);
					intent.putStringArrayListExtra("urls",
							currentSeller.sellerPics);
					intent.putExtra("position", position + "");
					startActivity(intent);
				}
			});
		} else {
			ImageView imgView = (ImageView) findViewById(R.id.seller_detail_img);
			gridView.setVisibility(View.GONE);
			imgView.setVisibility(View.VISIBLE);
		}
		// ImageLoader imageLoader = new ImageLoader();
		// imageLoader.showImageAsyn(sellerPic, CarmapApplication.SERVER_URL +
		// "/images/" + currentSeller.sellerPic, loading,
		// R.drawable.no_seller_pic);
		// sellerPic.setOnClickListener(new OnClickListener() {
		//
		// @Override
		// public void onClick(View v) {
		// if(currentSeller.sellerPics!=null&&currentSeller.sellerPics.size()>0){
		// Intent in = new Intent();
		// in.putStringArrayListExtra("url", currentSeller.sellerPics);
		// in.setClass(SellerActivity.this, GridPicActivity.class);
		// startActivity(in);
		//
		// }
		// }
		// });
		sellerName.setText(currentSeller.sellerName);
		// distance.setText("距离："+currentSeller.distance);
		address.setText("地址：" + currentSeller.address);
		call.setText("电话：" + phone);
		description.setText(currentSeller.description);
		ListView listView = (ListView) findViewById(R.id.service_list_view);
		List<ServiceItem> serviceItems = currentSeller.serviceItems;
		if (serviceItems != null && serviceItems.size() > 0) {
			listView.setAdapter(new ServiceItemListAdapter(
					currentSeller.serviceItems));
		} else {
			listView.setVisibility(View.INVISIBLE);
		}
		// countPic.setText("共" + currentSeller.sellerPics.size() + "张");
		listView.setOnItemClickListener(this);
	}

	@SuppressWarnings("deprecation")
	private void initMenuItem() {
/*		if ("type".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_type);
			menuItem.setBackgroundDrawable(getApplication().getResources()
					.getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this
					.findViewById(R.id.item_type_image);
			itemImage.setImageResource(R.drawable.type_select);
			// 底部菜单文字
			TextView itemText = (TextView) this
					.findViewById(R.id.item_type_text);
			itemText.setTextColor(getApplication().getResources().getColor(
					R.color.white));
		}*/
		// else if ("search".equals(CarmapApplication.currentPage)) {
		// // 底部菜单项
		// View menuItem = this.findViewById(R.id.menu_item_search);
		// menuItem.setBackgroundDrawable(getApplication().getResources().getDrawable(R.drawable.bottom_background));
		// // 底部菜单图标
		// ImageView itemImage = (ImageView)
		// this.findViewById(R.id.item_search_image);
		// itemImage.setImageResource(R.drawable.search_select);
		// // 底部菜单文字
		// TextView itemText = (TextView)
		// this.findViewById(R.id.item_search_text);
		// itemText.setTextColor(getApplication().getResources().getColor(R.color.white));
		// }
	/*	else if ("mine".equals(CarmapApplication.currentPage)) {
			// 底部菜单项
			View menuItem = this.findViewById(R.id.menu_item_mine);
			menuItem.setBackgroundDrawable(getApplication().getResources()
					.getDrawable(R.drawable.bottom_background));
			// 底部菜单图标
			ImageView itemImage = (ImageView) this
					.findViewById(R.id.item_mine_image);
			itemImage.setImageResource(R.drawable.mine_select);
			// 底部菜单文字
			TextView itemText = (TextView) this
					.findViewById(R.id.item_mine_text);
			itemText.setTextColor(getApplication().getResources().getColor(
					R.color.white));
		}*/
		// else if ("more".equals(CarmapApplication.currentPage)) {
		// // 底部菜单项
		// View menuItem = this.findViewById(R.id.menu_item_more);
		// menuItem.setBackgroundDrawable(getApplication().getResources().getDrawable(R.drawable.bottom_background));
		// // 底部菜单图标
		// ImageView itemImage = (ImageView)
		// this.findViewById(R.id.item_more_image);
		// itemImage.setImageResource(R.drawable.more_select);
		// // 底部菜单文字
		// TextView itemText = (TextView)
		// this.findViewById(R.id.item_more_text);
		// itemText.setTextColor(getApplication().getResources().getColor(R.color.white));
		// }
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		View view = (View) this.findViewById(R.id.menu_item_home);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				AutoServiceProcess process = new AutoServiceProcess();
				process.setContext(SellerActivity.this);
				process.getSellerTypes();
			}

		});

		view = (View) this.findViewById(R.id.menu_item_type);
		view.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				LiveServiceProcess process = new LiveServiceProcess();
				process.setContext(SellerActivity.this);
				process.getSellerTypes();
			}

		});

		view = (View) this.findViewById(R.id.menu_item_mine);
		view.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
//				UserInfo userInfo = CarmapApplication.getInstance().userInfo;
//				if (userInfo == null) {
//					SellerActivity.this.startActivity(new Intent(
//							SellerActivity.this, LoginActivity.class));
//				} else {
//					SellerActivity.this.startActivity(new Intent(
//							SellerActivity.this, ProfileActivity.class));
//				}
				SellerActivity.this.startActivity(new Intent(
						SellerActivity.this, MineInfoActivity.class));
			}

		});

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// 分类
		if (item.getTitle().equals("分类")) {
			SellerTypeProcess process = new SellerTypeProcess();
			process.setContext(this);
			process.getSellerTypes();
			this.finish();
		} else if (item.getTitle().equals("搜索")) {
			this.startActivity(new Intent(this, SellerSearchActivity.class));
			this.finish();
		}

		return true;
	}

	private class ServiceItemListAdapter extends BaseAdapter {
		View[] itemsView;

		public ServiceItemListAdapter(List<ServiceItem> list) {
			itemsView = new View[list.size()];
			for (int i = 0; i < list.size(); i++) {
				itemsView[i] = makeView(list.get(i));
			}
		}

		@Override
		public int getCount() {
			return itemsView.length;
		}

		@Override
		public Object getItem(int position) {
			return itemsView[position];
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			return itemsView[position];
		}

		private View makeView(ServiceItem service) {
			LayoutInflater inflater = (LayoutInflater) SellerActivity.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View itemView = inflater.inflate(R.layout.listitem_service, null);
			// ImageView imageView = (ImageView)
			// itemView.findViewById(R.id.img);
			TextView name = (TextView) itemView.findViewById(R.id.service_name);
			name.setText(service.serviceItemName);
			TextView detail = (TextView) itemView.findViewById(R.id.seivcePice);
			detail.setText("/" + service.servicePrice + "元");

			return itemView;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int index,
			long arg3) {
		// super.onListItemClick(l, v, position, id);
		Intent intent = new Intent(SellerActivity.this,
				ServiceItemActivity.class);
		if (currentSeller != null) {
			ServiceItem item = currentSeller.serviceItems.get(index);
			intent.putExtra("currentServiceItem", item);
			startActivity(intent);
		}
	}

	/**
	 * 开始导航
	 * 
	 * @param view
	 */
	public void startNavi(View view, double targetLat, double targetLon) {
		int lat = (int) (CarmapApplication.getInstance().getLocData().latitude * 1E6);
		int lon = (int) (CarmapApplication.getInstance().getLocData().longitude * 1E6);
		GeoPoint pt1 = new GeoPoint(lat, lon);
		lat = (int) (targetLat * 1E6);
		lon = (int) (targetLon * 1E6);
		GeoPoint pt2 = new GeoPoint(lat, lon);
		Intent intent = new Intent(this, RoutePlanActivity.class);
		intent.putExtra("startPosLat", pt1.getLatitudeE6());
		intent.putExtra("startPosLng", pt1.getLongitudeE6());
		intent.putExtra("endPosLat", pt2.getLatitudeE6());
		intent.putExtra("endPosLng", pt2.getLongitudeE6());
		this.startActivity(intent);
	}

	public void startWebNavi(View view, double targetLat, double targetLon) {
		int lat = (int) (CarmapApplication.getInstance().getLocData().latitude * 1E6);
		int lon = (int) (CarmapApplication.getInstance().getLocData().longitude * 1E6);
		GeoPoint pt1 = new GeoPoint(lat, lon);
		lat = (int) (targetLat * 1E6);
		lon = (int) (targetLon * 1E6);
		GeoPoint pt2 = new GeoPoint(lat, lon);
		// 构建 导航参数
		NaviPara para = new NaviPara();
		para.startPoint = pt1;
		para.endPoint = pt2;
		BaiduMapNavigation.openBaiduMapNavi(para, this);
	}

	@Override
	protected void onResume() {
		super.onResume();

		CarmapApplication.currentPage = "search";
	}

	static class ViewHolder {
		ImageView imageView;
		ProgressBar progressBar;
	}

	public class ImageAdapter extends BaseAdapter {
		@Override
		public int getCount() {
			return currentSeller.sellerPics.size();
		}

		@Override
		public Object getItem(int position) {
			return null;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final ViewHolder holder;
			View view = convertView;
			if (view == null) {
				view = getLayoutInflater().inflate(R.layout.item_grid_image,
						parent, false);
				holder = new ViewHolder();
				assert view != null;
				holder.imageView = (ImageView) view.findViewById(R.id.image);
				holder.progressBar = (ProgressBar) view
						.findViewById(R.id.progress);
				view.setTag(holder);
			} else {
				holder = (ViewHolder) view.getTag();
			}
			ImgUtil.loadImage(holder.imageView,CarmapApplication.SERVER_URL + "/images/"+ currentSeller.sellerPics.get(position),new SimpleImageLoadingListener(){
				 public void onLoadingStarted(String imageUri, View view) {
					 holder.progressBar.setVisibility(View.VISIBLE);
				 }
				 
				 public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
					 holder.progressBar.setVisibility(View.GONE);
				 }
			},SellerActivity.this);
			
		//	imageLoader.showImageAsyn(holder.imageView,CarmapApplication.SERVER_URL + "/images/"+ currentSeller.sellerPics.get(position),holder.progressBar, R.drawable.no_seller_pic);
			/*
			 * imageLoader.displayImage(imageUrls.get(position),
			 * holder.imageView, options, new SimpleImageLoadingListener() {
			 * 
			 * @Override public void onLoadingStarted(String imageUri, View
			 * view) { holder.progressBar.setProgress(0);
			 * holder.progressBar.setVisibility(View.VISIBLE); }
			 * 
			 * @Override public void onLoadingFailed(String imageUri, View view,
			 * FailReason failReason) {
			 * holder.progressBar.setVisibility(View.GONE); }
			 * 
			 * @Override public void onLoadingComplete(String imageUri, View
			 * view, Bitmap loadedImage) {
			 * holder.progressBar.setVisibility(View.GONE); } }, new
			 * ImageLoadingProgressListener() {
			 * 
			 * @Override public void onProgressUpdate(String imageUri, View
			 * view, int current, int total) {
			 * holder.progressBar.setProgress(Math.round(100.0f * current /
			 * total)); } } );
			 */
			return view;
		}
	}
}
